﻿using Aspose.Words;
using Aspose.Words.Tables;
using Newtonsoft.Json.Linq;
using QJY.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace QJY.API
{
    public class FILEManage
    {

        /// <summary>
        /// 按照WORD导出模板导出数据,.NETFRAMEWOK专用
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void EXPORTWORD(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo, HttpContext contexthttp)
        {
            int pdid = 0;
            int.TryParse(P1, out pdid);

            int piid = 0;
            int.TryParse(P2, out piid);
            Yan_WF_PD PD = new Yan_WF_PDB().GetEntity(d => d.ID == pdid && d.ComId == UserInfo.User.ComId);
            Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == piid && d.ComId == UserInfo.User.ComId);

            if (PD.ExportFile != null)
            {
                Dictionary<string, string> dictSource = new Dictionary<string, string>();

                List<JH_Auth_ExtendMode> ExtendModes = new List<JH_Auth_ExtendMode>();
                ExtendModes = new JH_Auth_ExtendModeB().GetEntities(D => D.ComId == UserInfo.User.ComId && D.PDID == pdid).ToList();
                foreach (JH_Auth_ExtendMode item in ExtendModes)
                {
                    // string strValue = new JH_Auth_ExtendDataB().GetFiledValue(item.TableFiledColumn, pdid, piid);
                    string strValue = new Yan_WF_PIB().GetFiledValByDC(PI.Content, item.TableFiledColumn);
                    dictSource.Add("qj_" + item.TableFiledColumn, strValue);
                }

                dictSource.Add("qj_CRUser", PI.CRUserName);
                dictSource.Add("qj_BranchName", PI.BranchName);
                dictSource.Add("qj_CRDate", PI.CRDate.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                dictSource.Add("qj_PINUM", PI.ID.ToString());


                List<Yan_WF_TI> tiModels = new Yan_WF_TIB().GetEntities(d => d.PIID == piid).ToList();
                for (int i = 0; i < tiModels.Count; i++)
                {
                    dictSource.Add("qj_Task" + i + ".TaskUser", new JH_Auth_UserB().GetUserRealName(UserInfo.User.ComId.Value, tiModels[i].TaskUserID));
                    dictSource.Add("qj_Task" + i + ".TaskUserView", tiModels[i].TaskUserView ?? "");
                    if (tiModels[i].EndTime != null)
                    {
                        dictSource.Add("qj_Task" + i + ".EndTime", tiModels[i].EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                }
                var basePath = HttpContext.Current.Request.MapPath("/");

                string filePath = basePath + "/" + PD.ExportFile;
                Aspose.Words.Document doc = new Aspose.Words.Document(filePath);




                //使用文本方式替换
                foreach (string name in dictSource.Keys)
                {
                    doc.Range.Replace(name, dictSource[name], false, false);
                }

                #region 使用书签替换模式


                #endregion
                string Filepath = basePath + "\\Export\\";
                string strFileName = PD.ProcessName + DateTime.Now.ToString("yyMMddHHss") + ".doc";

                doc.Save(Filepath + strFileName, Aspose.Words.Saving.DocSaveOptions.CreateSaveOptions(SaveFormat.Doc));
                msg.Result = strFileName;
                //contexthttp.Response.ContentType = "application/x-zip-compressed";
                //contexthttp.Response.AddHeader("Content-type", "text/html;charset=UTF-8");
                //contexthttp.Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
                ////string filename = Server.MapPath("/" + attch.FileUrl);
                //contexthttp.Response.TransmitFile(Filepath + strFileName);
                //contexthttp.Response.End();

            }
        }



        /// <summary>
        /// 上传头像.NETFRAMEWOK专用
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void UPTX(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo, HttpContext contexthttp)
        {

            var files = contexthttp.Request.Files;
            int size = files[0].ContentLength;

            if (size > 5485760)
            {
                msg.ErrorMsg = "大小不能超过5M";
            }

            List<string> filePathResultList = new List<string>();
            for (int i = 0; i < contexthttp.Request.Files.Count; i++)
            {

                HttpPostedFile uploadFile = contexthttp.Request.Files[i];

                string originalName = uploadFile.FileName;
                string[] temp = uploadFile.FileName.Split('.');
                string filename = UserInfo.User.UserName + "." + temp[temp.Length - 1].ToLower();
                uploadFile.SaveAs(HttpContext.Current.Request.MapPath("~/upload/tx/" + filename));
                filePathResultList.Add("/upload/tx/" + filename);

            }
            msg.Result = filePathResultList;

        }


        /// <summary>
        /// 按照WORD导出模板导出数据,.NETFRAMEWOK专用
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void EXWORD(JObject context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo, HttpContext contexthttp)
        {

            var basePath = HttpContext.Current.Request.MapPath("/");

            string filePath = basePath + "/upload/dcmb/dymd.docx";
            Aspose.Words.Document doc = new Aspose.Words.Document(filePath);


            DataTable DTPD = new QJ_JWB().GetDTByCommand("SELECT top 1000 bj,xh,xm,kcmc,bkjse,'1' as zwh,kslb FROM Bkbm where kslb<>'' and bkjse<>''");
            //DTPD.TableName = "kcmd";
            //doc.MailMerge.ExecuteWithRegions(DTPD);


            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.MoveToBookmark("START");
            ////移动焦点到文档最后,获得原来的页数
            //builder.MoveToDocumentEnd();
            //int oldPageCount = doc.PageCount;
            ////循环加换行，直到页数发生变化为止
            //while (oldPageCount < doc.PageCount)
            //{
            //    builder.Writeln();
            //}
            dcDatable(doc, builder, DTPD, "班级,学号,姓名,课程,考场,座位号,补考类别");
            string Filepath = basePath + "\\Export\\";
            string strFileName = DateTime.Now.ToString("yyMMddHHss") + ".doc";

            doc.Save(Filepath + strFileName, Aspose.Words.Saving.DocSaveOptions.CreateSaveOptions(SaveFormat.Doc));
            msg.Result = strFileName;

        }



        public DocumentBuilder dcDatable(Aspose.Words.Document doc, DocumentBuilder builder, DataTable dt, String strcol)
        {




            Table table = builder.StartTable();

            foreach (String item in strcol.Split(','))
            {
                builder.InsertCell();
                builder.Font.Size = 9;
                builder.Font.Name = "宋体";
                builder.Font.Bold = true;
                builder.Write(item);
            }
            builder.EndRow();

            builder.Font.Bold = false;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int m = 0; m < dt.Columns.Count; m++)
                {
                    builder.InsertCell();
                    builder.Font.Size = 10;
                    builder.Font.Name = "宋体";
                    builder.Write(dt.Rows[i][m].ToString());
                }
                builder.EndRow();
            }
            builder.EndTable();




            // Make the header row.
            //builder.InsertCell();

            //// Set the left indent for the table. Table wide formatting must be applied after
            //// at least one row is present in the table.
            //table.LeftIndent = 20.0;

            //// Set height and define the height rule for the header row.
            //builder.RowFormat.Height = 40.0;
            //builder.RowFormat.HeightRule = HeightRule.AtLeast;

            //// Some special features for the header row.
            //// builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241);
            //builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            //builder.Font.Size = 16;
            //builder.Font.Name = "Arial";
            //builder.Font.Bold = true;

            //builder.CellFormat.Width = 100.0;
            //builder.Write("Header Row,\n Cell 1");

            //// We don't need to specify the width of this cell because it's inherited from the previous cell.
            //builder.InsertCell();
            //builder.Write("Header Row,\n Cell 2");

            //builder.InsertCell();
            //builder.CellFormat.Width = 200.0;
            //builder.Write("Header Row,\n Cell 3");
            //builder.EndRow();

            //// Set features for the other rows and cells.
            //// builder.CellFormat.Shading.BackgroundPatternColor = Color.White;
            //builder.CellFormat.Width = 100.0;
            //builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

            //// Reset height and define a different height rule for table body
            //builder.RowFormat.Height = 30.0;
            //builder.RowFormat.HeightRule = HeightRule.Auto;
            //builder.InsertCell();
            //// Reset font formatting.
            //builder.Font.Size = 12;
            //builder.Font.Bold = false;

            //// Build the other cells.
            //builder.Write("Row 1, Cell 1 Content");
            //builder.InsertCell();
            //builder.Write("Row 1, Cell 2 Content");

            //builder.InsertCell();
            //builder.CellFormat.Width = 200.0;
            //builder.Write("Row 1, Cell 3 Content");
            //builder.EndRow();

            //builder.InsertCell();
            //builder.CellFormat.Width = 100.0;
            //builder.Write("Row 2, Cell 1 Content");

            //builder.InsertCell();
            //builder.Write("Row 2, Cell 2 Content");

            //builder.InsertCell();
            //builder.CellFormat.Width = 200.0;
            //builder.Write("Row 2, Cell 3 Content.");
            //builder.EndRow();
            //builder.EndTable();
            return builder;
        }
    }
}